import validate from 'wechat-validate'
Page({
  // 混入
  // 将插件注入到页面实例中
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile:'15922439908',
    code:''
  },
  rules:{
    mobile: [
      {required: true, message: '请填写手机号码!'},
      {pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!'}
    ],
    code: [
      {required: true, message: '请填写验证码!'},
      {pattern: /^\d{6}$/, message: '请填写正确的验证码!'}
    ]
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 点击倒计时
  async getMSCode(){
    // 表单校验
    const {valid,message}=this.validate('mobile')
    if(!valid) return wx.utils.toast(message)
    // 展示倒计时
    this.setData({
      countDownVisible:true
    })
    // 获取验证码
    const {code}=await wx.http.get('/code',{mobile:this.data.mobile})
    // console.log(code)
    this.setData({code})//实际工作中应该有用户输入
  },
  // 登录
  async submitForm(){
    // 1.表单的完整校验
    const flag=this.validate()
    if(!flag) return
    // 2.发送请求
    const res=await wx.http.post('/login',{
      code:this.data.code,
      mobile:this.data.mobile
    })
    // console.log(res)
    // 3.提示成功
    wx.utils.toast('登陆成功','success')
    // 4.存储token
    const app=getApp()
    app.setToken('token',res.token)
    app.setToken('refreshToken',res.refreshToken)
    // 5。跳转页面
    wx.redirectTo({
      url:'/'+this.redirectUrl
    })
  },
  // 获取跳转路径
 onLoad({redirectUrl}){
  //  console.log(options)
  this.redirectUrl=redirectUrl
 }
})
